package de.hoits.app.gewichtskontolle.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DbAdapter
{

	// Database fields
	public static final String KEY_ROWID = "id";
	public static final String KEY_MEINGEWICHT = "meinGewicht"; //Float
	public static final String KEY_DATUM = "datum"; //Datetime
	public static final String KEY_DESCRIPTION = "description";
	
	private static final String DATABASE_TABLE = "gewicht";
	
	private Context context;
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;

	public DbAdapter(Context context)
	{
		this.context = context;
	}

	public DbAdapter open() throws SQLException 
	{
		dbHelper = new DatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() 
	{
		dbHelper.close();
	}

	/**
	 * Create a new GewichtEintrag If the GewichtEintrag is successfully created return the new
	 * rowId for that note, otherwise return a -1 to indicate failure.
	 */
	public long createGewichtEintrag(String gewicht, String datetime, String description) 
	{
		ContentValues initialValues = createContentValues(gewicht, datetime, description);
		return database.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Update the GewichtEintrag
	 */
	public boolean updateGewichtEintrag(long rowId, String gewicht, String datetime, String description) 
	{
		ContentValues updateValues = createContentValues(gewicht, datetime, description);

		return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "="
				+ rowId, null) > 0;
	}

	/**
	 * Deletes GewichtEintrag
	 */
	public boolean deleteGewichtEintrag(long rowId)
	{
		return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all todo in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor fetchAllGewichtEintrag()
	{
		return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_MEINGEWICHT, KEY_DATUM, KEY_DESCRIPTION }, null, null, null,
				null, null);
	}

	/**
	 * Return a Cursor positioned at the defined todo
	 */
	public Cursor fetchGewichtEintrag(long rowId) throws SQLException 
	{
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_MEINGEWICHT, KEY_DATUM, KEY_DESCRIPTION },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		
		if (mCursor != null) 
		{
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	private ContentValues createContentValues(String gewicht, String datum, String description) 
	{
		ContentValues values = new ContentValues();
		values.put(KEY_MEINGEWICHT, gewicht);
		values.put(KEY_DATUM, datum);
		values.put(KEY_DESCRIPTION, description);
		return values;
	}
}

